package com.test.demo.controller;

import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Component
public class ScheduledApiTask {
    
    private final RestTemplate restTemplate = new RestTemplate();

    public static void main(String[] args) {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
        System.out.println("当前项目工作目录: "+System.getProperty("user.dir"));
        // 手动调用API（绕过Spring依赖注入）
        ScheduledApiTask task = new ScheduledApiTask();
        task.callApiWithRestTemplate();
    }

    private static final String API_URL = "http://iip.bxgt.com/di-api/dacoo-api/openApi/exDataManage/queryByAttrIds?appKey=250221153244004500001";
    
    @Scheduled(fixedRate = 30000)
    public void callApiWithRestTemplate() {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        Map<String, Object> mapValue = new HashMap<>();
        mapValue.put("244707", Collections.emptyList());
        requestBody.put("map", mapValue);
        requestBody.put("startTime", "1757001600000");
        requestBody.put("endTime", "1757039706373");

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送 POST 请求
            ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, requestEntity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                System.out.println("API 调用成功: " + response.getBody());
            } else {
                System.err.println("API 调用失败，状态码: " + response.getStatusCode());
                System.err.println("响应内容: " + response.getBody());
            }
        } catch (Exception e) {
            System.err.println("调用API时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

}